package com.xxxy.ljh.myapplication.nav;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.xxxy.ljh.myapplication.Dao.UserDao;
import com.xxxy.ljh.myapplication.DaoImpl.UserDaoImpl;
import com.xxxy.ljh.myapplication.MainActivity;
import com.xxxy.ljh.myapplication.Manager.UserManager;
import com.xxxy.ljh.myapplication.R;
import com.xxxy.ljh.myapplication.activity.AssociationManagementActivity;
import com.xxxy.ljh.myapplication.activity.ClubApplicationReviewActivity;
import com.xxxy.ljh.myapplication.activity.ClubAuditActivity;
import com.xxxy.ljh.myapplication.activity.ItemListActivity;
import com.xxxy.ljh.myapplication.activity.MemberApplicationReviewActivity;
import com.xxxy.ljh.myapplication.activity.SuperListActivity;
import com.xxxy.ljh.myapplication.activity.login.LoginActivity;
import com.xxxy.ljh.myapplication.model.User;
import com.xxxy.ljh.myapplication.Dao.ClubDao;
import com.xxxy.ljh.myapplication.DaoImpl.ClubDaoImpl;

public class MineFragment extends Fragment {
    public static final int LOGIN_REQUEST_CODE = 1001;

    // UI组件
    private LinearLayout layoutNotLoggedIn;
    private ScrollView layoutLoggedIn;
    private Button btnLoginPrompt;
    private Button btnLogout;
    private TextView tvUsername;
    private TextView tvStudentId;
    private Button btnAllMembers;
    private Button btnAssociationManagement;
    private Button btnClubAudit;
    private Button btnItemList;
    private Button btnSettings;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        initViews(view);
        setupListeners();
        updateProfileUI();

        return view;

    }

    @SuppressLint("WrongViewCast")
    private void initViews(View view) {
        layoutNotLoggedIn = view.findViewById(R.id.layout_not_logged_in);
        layoutLoggedIn = view.findViewById(R.id.layout_logged_in);
        btnLoginPrompt = view.findViewById(R.id.btn_login_prompt);
        btnLogout = view.findViewById(R.id.btn_logout);
        tvUsername = view.findViewById(R.id.tv_username);
        tvStudentId = view.findViewById(R.id.tv_student_id);
        btnAllMembers = view.findViewById(R.id.btn_all_members);
        btnAssociationManagement = view.findViewById(R.id.btn_association_management);
        btnClubAudit = view.findViewById(R.id.btn_club_audit);
        btnItemList = view.findViewById(R.id.btnItemList);
        btnSettings = view.findViewById(R.id.btn_settings);
    }

    private void setupListeners() {
        btnLoginPrompt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, LOGIN_REQUEST_CODE);
            }
        });
//用户登出
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清除所有登录相关的信息
                SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
                prefs.edit().clear().apply();
                // 清除所有存储的数据
                UserManager.getInstance(getContext()).logoutUser();
                updateProfileUI();
                Toast.makeText(getContext(), "已退出登录", Toast.LENGTH_SHORT).show();
            }
        });

        // 新增：查询所有成员按钮点击事件
        btnAllMembers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SuperListActivity.class);
                startActivity(intent);
            }
        });
        btnAssociationManagement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AssociationManagementActivity.class);
                // 可以传递用户信息和社团信息
                // intent.putExtra("user", user);
                startActivity(intent);
            }
        });
        // 添加社团成员申请审核按钮点击事件
        btnClubAudit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户管理的社团ID
                SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
                // 首先尝试获取用户创建的社团ID
                int managedClubId = prefs.getInt("managed_club_id", -1);
                
                // 如果没有找到创建的社团，则尝试获取用户作为社长管理的社团
                if (managedClubId == -1) {
                    managedClubId = getManagedClubId();
                }
                
                if (managedClubId == -1) {
                    Toast.makeText(getContext(), "您尚未创建或管理任何社团", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                Intent intent = new Intent(getActivity(), MemberApplicationReviewActivity.class);
                intent.putExtra("club_id", managedClubId);
                startActivity(intent);
            }
        });
        btnItemList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ItemListActivity.class);
                startActivity(intent);
            }
        });
        // 设置按钮点击事件
        btnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), com.xxxy.ljh.myapplication.activity.login.SettingsActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取用户管理的社团ID
     * @return 社团ID，如果未找到则返回-1
     */
    private int getManagedClubId() {
        // 获取当前登录用户
        SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
        boolean isLoggedIn = prefs.getBoolean("is_logged_in", false);
        
        if (!isLoggedIn) {
            return -1;
        }
        
        int userId = prefs.getInt("user_id", -1);
        if (userId == -1) {
            return -1;
        }
        
        // 查询数据库获取用户管理的社团
        ClubDao clubDao = new ClubDaoImpl(getContext());
        return clubDao.getClubIdByFounderId(userId);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOGIN_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
            if (data != null) {
                String username = data.getStringExtra("logged_in_user");
                if (username != null) {
                    // 保存登录状态
                    SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
                    prefs.edit()
                            .putBoolean("is_logged_in", true)  // 确保设置为true
                            .putString("username", username)
                            .apply();

                    updateProfileUI();
                }
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        updateProfileUI(); // 每次页面可见时都刷新状态
    }

    private void updateProfileUI() {
        SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
        boolean isLoggedIn = prefs.getBoolean("is_logged_in", false);

        if (isLoggedIn) {
            String username = prefs.getString("username", "");

            // 获取用户详细信息
            UserDao userDao = new UserDaoImpl(getContext());
            User user = userDao.getUserByUsername(username);

            layoutNotLoggedIn.setVisibility(View.GONE);
            layoutLoggedIn.setVisibility(View.VISIBLE);

            if (user != null) {
                tvUsername.setText(user.getRealName()); // 显示真实姓名而不是用户名
                tvStudentId.setText("学号: " + user.getStudentId());
                // 根据用户角色显示不同按钮
                if (user.getRole() == 0) {
                    // 普通用户
                    btnAllMembers.setVisibility(View.GONE);
                    btnAssociationManagement.setVisibility(View.GONE);
                    btnClubAudit.setVisibility(View.GONE);
                } else if (user.getRole() == 1) {
                    // 部长用户
                    btnAllMembers.setVisibility(View.GONE);
                    btnAssociationManagement.setVisibility(View.VISIBLE);
                    btnClubAudit.setVisibility(View.VISIBLE);
                } else if(user.getRole() == 3|| user.getRole() == 2) {
                    // 管理员和超级管理员
                    btnAllMembers.setVisibility(View.VISIBLE);
                    btnAssociationManagement.setVisibility(View.GONE);
                    btnClubAudit.setVisibility(View.VISIBLE);
                }else {
                    Toast.makeText(getContext(),"请先登录", Toast.LENGTH_SHORT);
                }
            }
        } else {
            layoutNotLoggedIn.setVisibility(View.VISIBLE);
            layoutLoggedIn.setVisibility(View.GONE);
        }

    }
}